# -*- coding: utf-8 -*-
import webapp2
import exceptions
import datetime

from event import Event
from webapp2 import uri_for
Types = [u'Укус насекомого', u'Травма', u'Выезд в город']
events_to_show = []

class ViewEvents(webapp2.RequestHandler):

    def get(self, *argc, **kwargs):
        global events_to_show
        self.response.write("<html><body>")
        found_event = (events_to_show != [])
        if not found_event:
            self.response.write('<h>'
                                'Не найдено ни одного события в интересующем вас промежутке времени'
                                '</h>')
        else:
            self.response.write('<h>'
                                "Интересующие вас события"
                                '</h>'
                                '<ul>')
            for event in events_to_show:
                self.response.write('<li>%s %s %s(%s) %s</li>'
                                    % (event.Surname, event.Name, event.Type, event.Comment, event.DateTime))
            self.response.write('</ul>')

        self.response.write("<br><strong>Добавить событие</strong>")
        self.response.write("""</ul>
        <form action="%s" method="post">
            <label for="event"></label> <br>
            <label for="surname">Фамилия<br></label>
                <input id="surname" type="text" name="person_surname"> <br>
            <label for="name">Имя<br></label>
                <input id="name" type="text" name="person_name"><br><br>
            <input type="radio" name="type" value="0">Укус насекомого<br>
            <input type="radio" name="type" value="1">Травма<br>
            <input type="radio" name="type" value="2">Выезд в город<br>
            <input type="text" name="comment">Что случилось?<br>
            <input type="datetime-local" name="date" value="%s">Когда это случилось<br>
            <input type="submit" value="Добавить">
        </form>
       """ % (uri_for('add'), str(datetime.datetime.today())))

        self.response.write('<strong> Укажите интересующий вас период и тип события</strong>')
        self.response.write("""
        <form action="%s" method="post">
            <label for="period">Интересующий период<br>
                <input type="datetime-local" name="start"> Начало <br>
                <input type="datetime-local" name="end"> Конец <br>
            </label>

            <label for="type"> Интересующий тип события(если ничего не указано, будут показаны все события) <br>
                <input type="radio" name="type" value="0">Укус насекомого<br>
                <input type="radio" name="type" value="1">Травма<br>
                <input type="radio" name="type" value="2">Выезд в город<br>
            </label>

            <input type="submit" value="Показать">
        </form>
        """ % (uri_for('reveal')))
        self.response.write('</body></html>')


class AddEvent(webapp2.RequestHandler):
    def __init__(self, *argc, **kwargs):
        super(AddEvent, self).__init__(*argc, **kwargs)

    def post(self, *argc, **kwargs):
        name = self.request.get('name')
        surname = self.request.get('surname')
        Type = self.request.get('type')
        comment = self.request.get('comment')
        date = self.request.get('date')

        date_list, time_list = date.split('T')
        date_list = date_list.split('-')
        time_list = time_list.split(':')
        DateTime = datetime.datetime(int(date_list[0]), int(date_list[1]), int(date_list[2]), int(time_list[0]), int(time_list[1]))

        new_event = Event(Surname=surname,
                          Name=name,
                          Comment=comment,
                          Type=Types[int(Type)],
                          DateTime=DateTime)
        events_to_show.append(new_event)
        new_event.put()
        self.redirect(uri_for('show'))

class RevealEvents(webapp2.RequestHandler):
    def __init__(self, *argc, **kwargs):
        super(RevealEvents, self).__init__(*argc, **kwargs)

    def post(self, *argc, **kwargs):
        global events_to_show
        start = self.request.get('start')
        end = self.request.get('end')

        start_date_list, start_time_list = start.split('T')
        start_date_list = start_date_list.split('-')
        start_time_list = start_time_list.split(':')
        start_DateTime = datetime.datetime(int(start_date_list[0]), int(start_date_list[1]), int(start_date_list[2]), int(start_time_list[0]), int(start_time_list[1]))

        end_date_list, end_time_list = end.split('T')
        end_date_list = end_date_list.split('-')
        end_time_list = end_time_list.split(':')
        end_DateTime = datetime.datetime(int(end_date_list[0]), int(end_date_list[1]), int(end_date_list[2]), int(end_time_list[0]), int(end_time_list[1]))

        need_type = self.request.get("type")
        events_to_show = []

        if need_type == "":
            for event in Event.query():
                if start_DateTime <= event.DateTime <= end_DateTime:
                    events_to_show.append(event)
        else:
            for event in Event.query():
                if start_DateTime <= event.DateTime <= end_DateTime and event.Type == Types[int(need_type)]:
                    events_to_show.append(event)

        self.redirect(uri_for('show'))